<template>
  <div class="inventory-container">
    <!-- 库存统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">
            <span>总商品数</span>
          </div>
          <div class="stats-number">{{ stats.totalProducts }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">
            <span>低库存商品</span>
            <el-tooltip content="库存数量低于或等于预警阈值的商品数量" placement="top">
              <i class="el-icon-question" style="margin-left: 5px;"></i>
            </el-tooltip>
          </div>
          <div class="stats-number warning">{{ stats.lowStockCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">
            <span>零库存商品</span>
          </div>
          <div class="stats-number danger">{{ stats.zeroStockCount }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input
            v-model="searchForm.productCode"
            placeholder="商品编码"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.productName"
            placeholder="商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.location"
            placeholder="库位"
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增库存</el-button>
          <el-button type="warning" @click="handleBatchUpdate">批量更新</el-button>
        </el-form-item>
      </el-form>
      <div class="stock-tip">
        <el-alert
          title="库存状态说明"
          type="info"
          :closable="false"
          description="绿色：库存正常 | 黄色：库存低于或等于预警阈值 | 红色：库存为0"
        />
      </div>
    </div>

    <!-- 库存列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column label="商品信息" width="300">
        <template slot-scope="scope">
          <div>
            <div>{{ scope.row.supplierName }} - {{ scope.row.productName }}</div>
            <div style="font-size: 12px; color: #909399;">
              编码：{{ scope.row.productCode }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="库位" width="120" />
      <el-table-column prop="quantity" label="当前库存" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStockTagType(scope.row)">
            {{ scope.row.quantity }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="warningThreshold" label="预警阈值" width="120" />
      <el-table-column label="操作" width="380">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="primary" 
            @click="handleUpdate(scope.row)"
          >更新库存</el-button>
          <el-button 
            size="mini" 
            type="success" 
            @click="handleUpdateInfo(scope.row)"
          >修改信息</el-button>
          <el-button 
            size="mini" 
            type="info" 
            @click="handleHistory(scope.row)"
          >库存记录</el-button>
          <el-button 
            size="mini" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />

    <!-- 更新库存对话框 -->
    <el-dialog title="更新库存" :visible.sync="updateDialogVisible" width="500px">
      <el-form :model="updateForm" ref="updateForm" :rules="updateRules" label-width="100px">
        <el-form-item label="商品编码">
          <span>{{ updateForm.productCode }}</span>
        </el-form-item>
        <el-form-item label="商品名称">
          <span>{{ updateForm.productName }}</span>
        </el-form-item>
        <el-form-item label="库位">
          <span>{{ updateForm.location }}</span>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{ updateForm.currentQuantity }}</span>
        </el-form-item>
        <el-form-item label="预警阈值">
          <span>{{ updateForm.warningThreshold }}</span>
        </el-form-item>
        <el-form-item label="调整数量" prop="adjustQuantity">
          <el-input-number 
            v-model="updateForm.adjustQuantity" 
            :min="-updateForm.currentQuantity"
            placeholder="正数增加/负数减少"
          />
          <div class="form-tip">注：正数增加库存，负数减少库存</div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改商品信息对话框 -->
    <el-dialog title="修改商品信息" :visible.sync="infoDialogVisible" width="500px">
      <el-form :model="infoForm" ref="infoForm" :rules="infoRules" label-width="100px">
        <el-form-item label="商品编码">
          <span>{{ infoForm.productCode }}</span>
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="infoForm.productName" />
        </el-form-item>
        <el-form-item label="库位" prop="location">
          <el-input v-model="infoForm.location" />
        </el-form-item>
        <el-form-item label="预警阈值" prop="warningThreshold">
          <el-input-number v-model="infoForm.warningThreshold" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="infoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitInfoUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 库存历史记录对话框 -->
    <el-dialog title="库存历史记录" :visible.sync="historyDialogVisible" width="800px">
      <div class="history-search">
        <el-date-picker
          v-model="historyDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 350px; margin-right: 10px;"
        />
        <el-button type="primary" @click="searchHistory" :loading="historyLoading">查询</el-button>
        <el-button @click="resetHistorySearch">重置</el-button>
      </div>
      <el-table 
        :data="historyData" 
        border 
        style="width: 100%"
        v-loading="historyLoading"
        element-loading-text="加载中..."
      >
        <el-table-column label="时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === '入库' ? 'success' : 'warning'">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.quantity >= 0 ? '#67C23A' : '#F56C6C' }">
              {{ scope.row.quantity >= 0 ? '+' : '' }}{{ scope.row.quantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNumber" label="单号" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="historyDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="供应商" prop="supplierId">
          <el-select 
            v-model="form.supplierId" 
            placeholder="请选择供应商"
            @change="handleSupplierChange"
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品" prop="productId">
          <el-select 
            v-model="form.productId" 
            placeholder="请选择商品"
            @change="handleProductChange"
            :disabled="!form.supplierId"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.productName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="0" />
        </el-form-item>
        <el-form-item label="库位" prop="location">
          <el-input v-model="form.location" />
        </el-form-item>
        <el-form-item label="预警阈值" prop="warningThreshold">
          <el-input-number v-model="form.warningThreshold" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量更新对话框 -->
    <el-dialog title="批量更新库存" :visible.sync="batchDialogVisible" width="800px">
      <div class="batch-tip">
        <el-alert
          title="批量更新说明"
          type="info"
          description="可以同时更新多个商品的库存，正数表示入库，负数表示出库"
          show-icon
          :closable="false"
        />
      </div>
      <el-table :data="batchUpdateList" border style="width: 100%">
        <el-table-column label="商品信息" width="300">
          <template slot-scope="scope">
            <div>{{ scope.row.supplierName }} - {{ scope.row.productName }}</div>
            <div style="font-size: 12px; color: #909399;">编码：{{ scope.row.productCode }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="currentQuantity" label="当前库存" width="120" />
        <el-table-column label="调整数量" width="200">
          <template slot-scope="scope">
            <el-input-number 
              v-model="scope.row.adjustQuantity" 
              :min="-scope.row.currentQuantity"
              placeholder="调整数量"
              @change="validateBatchUpdate(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button 
              type="danger" 
              size="mini" 
              icon="el-icon-delete"
              @click.native.prevent="removeBatchItem(scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="batchDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitBatchUpdate" :loading="batchUpdateLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'InventoryManage',
  data() {
    return {
      // 表格数据
      tableData: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 统计数据
      stats: {
        totalProducts: 0,
        lowStockCount: 0,
        zeroStockCount: 0
      },
      // 搜索表单
      searchForm: {
        productCode: '',
        productName: '',
        location: '',
        supplierId: null
      },
      // 更新库存对话框
      updateDialogVisible: false,
      updateForm: {
        productCode: '',
        productName: '',
        location: '',
        currentQuantity: 0,
        warningThreshold: 0,
        adjustQuantity: 0
      },
      updateRules: {
        adjustQuantity: [
          { required: true, message: '请输入调整数量', trigger: 'blur' }
        ]
      },
      // 修改信息对话框
      infoDialogVisible: false,
      infoForm: {
        productCode: '',
        productName: '',
        location: '',
        warningThreshold: 0
      },
      infoRules: {
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请输入库位', trigger: 'blur' }
        ],
        warningThreshold: [
          { required: true, message: '请输入预警阈值', trigger: 'blur' }
        ]
      },
      // 历史记录对话框
      historyDialogVisible: false,
      historyDateRange: [],
      historyData: [],
      currentProductCode: '', // 当前查看历史记录的商品编码
      supplierOptions: [],
      productOptions: [],
      form: {
        id: null,
        supplierId: null,
        productId: null,
        quantity: 0,
        location: '',
        warningThreshold: 0
      },
      rules: {
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        productId: [
          { required: true, message: '请选择商品', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请输入库位', trigger: 'blur' }
        ],
        warningThreshold: [
          { required: true, message: '请输入预警阈值', trigger: 'blur' }
        ]
      },
      dialogTitle: '',
      dialogVisible: false,
      historyLoading: false,
      // 批量更新相关
      batchDialogVisible: false,
      batchUpdateList: [],
      batchUpdateLoading: false
    }
  },
  created() {
    this.fetchData()
    this.fetchStats()
    this.fetchSuppliers()
  },
  methods: {
    // 获取库存列表
    async fetchData() {
      try {
        const res = await request({
          url: '/inventory/page',
          method: 'get',
          params: {
            current: this.currentPage,
            size: this.pageSize,
            ...this.searchForm
          }
        })
        if (res.code === 200) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      } catch (error) {
        this.$message.error('获取库存列表失败')
      }
    },

    // 获取统计数据
    async fetchStats() {
      try {
        const res = await request({
          url: '/inventory/stats',
          method: 'get'
        })
        if (res.code === 200) {
          this.stats = res.data
          // 如果有低库存或零库存商品，显示警告提示
          if (this.stats.lowStockCount > 0 || this.stats.zeroStockCount > 0) {
            let warningMessage = ''
            if (this.stats.zeroStockCount > 0) {
              warningMessage = `${this.stats.zeroStockCount}个商品库存为0`
            } else {
              warningMessage = `有${this.stats.lowStockCount}个商品库存低于或等于预警阈值`
            }
            
            this.$notify({
              title: '库存预警',
              message: warningMessage,
              type: 'warning',
              duration: 5000,
              position: 'top-right'
            })
          }
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$message.error('获取统计数据失败')
      }
    },

    // 处理搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        productCode: '',
        productName: '',
        location: '',
        supplierId: null
      }
      this.handleSearch()
    },

    // 获取库存标签类型
    getStockTagType(row) {
      if (row.quantity === 0) {
        return 'danger'
      }
      if (row.quantity <= row.warningThreshold) {
        return 'warning'
      }
      return 'success'
    },

    // 处理分页
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },

    // 处理更新库存
    handleUpdate(row) {
      this.updateForm = {
        productCode: row.productCode,
        productName: row.productName,
        location: row.location,
        currentQuantity: row.quantity,
        warningThreshold: row.warningThreshold,
        adjustQuantity: 0
      }
      this.updateDialogVisible = true
    },

    // 提交库存更新
    async submitUpdate() {
      this.$refs.updateForm.validate(async (valid) => {
        if (valid) {
          try {
            // 计算更新后的库存
            const updatedQuantity = this.updateForm.currentQuantity + this.updateForm.adjustQuantity
            
            // 如果是出库操作且更新后库存等于预警阈值，显示确认对话框
            if (this.updateForm.adjustQuantity < 0 && updatedQuantity === this.updateForm.warningThreshold) {
              try {
                await this.$confirm(
                  `出库后库存将等于预警阈值(${this.updateForm.warningThreshold})，是否继续？`,
                  '库存预警',
                  {
                    confirmButtonText: '继续出库',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }
                )
              } catch (error) {
                return // 用户取消操作
              }
            }

            const res = await request({
              url: '/inventory/update',
              method: 'post',
              params: {
                productCode: this.updateForm.productCode,
                adjustQuantity: this.updateForm.adjustQuantity
              }
            })
            if (res.code === 200) {
              this.$message.success('更新库存成功')
              this.updateDialogVisible = false
              await this.fetchData()
              await this.fetchStats()
              
              // 检查更新后的库存是否达到或低于预警阈值
              if (updatedQuantity <= this.updateForm.warningThreshold) {
                this.$notify({
                  title: '库存预警',
                  message: `商品 ${this.updateForm.productName} 的库存(${updatedQuantity})已${updatedQuantity === this.updateForm.warningThreshold ? '等于' : '低于'}预警阈值(${this.updateForm.warningThreshold})`,
                  type: 'warning',
                  duration: 5000,
                  position: 'top-right'
                })
              }
            }
          } catch (error) {
            this.$message.error(error.response?.data?.msg || '更新库存失败')
          }
        }
      })
    },

    // 处理修改信息
    handleUpdateInfo(row) {
      this.infoForm = {
        id: row.id,
        productCode: row.productCode,
        productName: row.productName,
        location: row.location,
        warningThreshold: row.warningThreshold
      }
      this.infoDialogVisible = true
    },

    // 提交信息更新
    async submitInfoUpdate() {
      this.$refs.infoForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await request({
              url: '/inventory/update-info',
              method: 'post',
              data: {
                id: this.infoForm.id,
                location: this.infoForm.location,
                warningThreshold: this.infoForm.warningThreshold
              }
            })
            if (res.code === 200) {
              this.$message.success('更新商品信息成功')
              this.infoDialogVisible = false
              await this.fetchData()
              await this.fetchStats()
            }
          } catch (error) {
            this.$message.error(error.response?.data?.msg || '更新商品信息失败')
          }
        }
      })
    },

    // 处理查看历史记录
    handleHistory(row) {
      this.currentProductCode = row.productCode
      this.historyDateRange = []
      this.historyData = []
      this.historyDialogVisible = true
      this.$nextTick(() => {
        this.searchHistory()
      })
    },

    // 重置历史记录搜索
    resetHistorySearch() {
      this.historyDateRange = []
      this.searchHistory()
    },

    // 搜索历史记录
    async searchHistory() {
      this.historyLoading = true
      try {
        const [startDate, endDate] = this.historyDateRange || []
        const params = {
          startDate: startDate || '',
          endDate: endDate || ''
        }
        
        const res = await request({
          url: `/inventory/history/${this.currentProductCode}`,
          method: 'get',
          params
        })
        if (res.code === 200) {
          this.historyData = res.data
        } else {
          this.$message.error(res.msg || '获取历史记录失败')
        }
      } catch (error) {
        console.error('获取历史记录失败:', error)
        this.$message.error(error.response?.data?.msg || '获取历史记录失败')
      } finally {
        this.historyLoading = false
      }
    },

    // 格式化日期时间
    formatDateTime(time) {
      return time || '--'
    },

    // 获取供应商列表
    async fetchSuppliers() {
      try {
        const res = await request({
          url: '/supplier/list',
          method: 'get'
        })
        if (res.code === 200) {
          this.supplierOptions = res.data
        }
      } catch (error) {
        this.$message.error('获取供应商列表失败')
      }
    },

    // 获取商品列表
    async fetchProducts(supplierId) {
      try {
        const res = await request({
          url: `/supplier-product/list/${supplierId}`,
          method: 'get'
        })
        if (res.code === 200) {
          this.productOptions = res.data
        }
      } catch (error) {
        this.$message.error('获取商品列表失败')
      }
    },

    // 供应商变更
    async handleSupplierChange(supplierId) {
      this.form.productId = null
      this.productOptions = []
      if (supplierId) {
        await this.fetchProducts(supplierId)
      }
    },

    // 商品变更
    handleProductChange(productId) {
      if (productId) {
        const product = this.productOptions.find(p => p.id === productId)
        if (product) {
          this.form = {
            ...this.form,
            productName: product.productName,
            productCode: product.productCode,
            productId: product.id
          }
        }
      }
    },

    // 修改新增方法
    handleAdd() {
      this.dialogTitle = '新增商品'
      this.form = {
        supplierId: null,
        productId: null,
        productName: '',
        productCode: '',
        remark: ''
      }
      this.dialogVisible = true
    },

    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            // 检查商品是否已存在
            const checkRes = await request({
              url: `/supplier-product/detail/${this.form.productId}`,
              method: 'get'
            })
            
            if (checkRes.code !== 200) {
              // 添加商品
              const res = await request({
                url: '/supplier-product/add',
                method: 'post',
                data: {
                  supplierId: this.form.supplierId,
                  productId: this.form.productId,
                  productName: this.form.productName,
                  productCode: this.form.productCode,
                  remark: this.form.remark || ''
                }
              })
              
              if (res.code === 200) {
                this.$message.success('新增商品成功，请通过入库单添加库存')
                this.dialogVisible = false
                await this.fetchData()
                await this.fetchStats()
              } else {
                throw new Error(res.msg || '新增商品失败')
              }
            } else {
              this.$message.warning('该商品已存在')
            }
          } catch (error) {
            console.error('新增商品失败:', error)
            this.$message.error(error.message || '新增商品失败')
          }
        }
      })
    },

    // 处理供应商筛选
    async handleSupplierFilter(supplierId) {
      if (supplierId) {
        try {
          const res = await request({
            url: `/inventory/by-supplier/${supplierId}`,
            method: 'get'
          })
          if (res.code === 200) {
            this.tableData = res.data.map(item => ({
              ...item.inventory,
              ...item.product,
              supplierName: this.getSupplierName(item.product.supplierId)
            }))
            this.total = this.tableData.length
          }
        } catch (error) {
          this.$message.error('获取供应商库存失败')
        }
      } else {
        this.fetchData()
      }
    },

    // 检查库存是否充足
    async checkStock(productId, quantity) {
      try {
        const res = await request({
          url: '/inventory/check-stock',
          method: 'post',
          data: {
            productId,
            quantity
          }
        })
        return res.code === 200 && res.data
      } catch (error) {
        this.$message.error('检查库存失败')
        return false
      }
    },

    // 处理批量更新
    handleBatchUpdate() {
      this.batchUpdateList = this.tableData.map(item => ({
        productId: item.productId,
        productCode: item.productCode,
        productName: item.productName,
        supplierName: item.supplierName,
        currentQuantity: item.quantity,
        adjustQuantity: 0
      }))
      this.batchDialogVisible = true
    },

    // 验证批量更新数据
    validateBatchUpdate(row) {
      if (row.adjustQuantity < -row.currentQuantity) {
        row.adjustQuantity = -row.currentQuantity
        this.$message.warning('调整数量不能小于当前库存的负数')
      }
    },

    // 移除批量更新项
    removeBatchItem(index) {
      this.batchUpdateList.splice(index, 1)
    },

    // 提交批量更新
    async submitBatchUpdate() {
      const updates = this.batchUpdateList
        .filter(item => item.adjustQuantity !== 0)
        .map(item => ({
          productId: item.productId,
          adjustQuantity: item.adjustQuantity
        }))

      if (updates.length === 0) {
        this.$message.warning('没有需要更新的数据')
        return
      }

      this.batchUpdateLoading = true
      try {
        const res = await request({
          url: '/inventory/batch-update',
          method: 'post',
          data: updates
        })
        
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.batchDialogVisible = false
          await this.fetchData()
          await this.fetchStats()
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error(error.response?.data?.msg || '批量更新失败')
      } finally {
        this.batchUpdateLoading = false
      }
    },

    // 修改删除方法
    async handleDelete(row) {
      try {
        await this.$confirm(
          '删除库存记录将同时删除该商品的所有库存历史记录，是否确认删除？', 
          '警告', 
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger'
          }
        )
        
        const res = await request({
          url: `/inventory/${row.id}`,
          method: 'delete'
        })
        
        if (res.code === 200) {
          this.$message.success('删除成功')
          await this.fetchData()
          await this.fetchStats()
        } else {
          throw new Error(res.msg || '删除库存失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除库存失败:', error)
          this.$message.error(error.response?.data?.msg || '删除失败，请确保该库存没有关联的历史记录')
        }
      }
    }
  }
}
</script>

<style scoped>
.inventory-container {
  padding: 20px;
}
.stats-row {
  margin-bottom: 20px;
}
.stats-number {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
}
.stats-number.warning {
  color: #E6A23C;
}
.stats-number.danger {
  color: #F56C6C;
}
.search-bar {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}
.stock-tip {
  margin-top: 10px;
}
.history-search {
  margin-bottom: 20px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 